//
//  LMScreenshotSington.swift
//  LMScreenshotHint
//
//  Created by LaiMing on 2021/4/19.
//

import Foundation
import UIKit

public class LMScreenshotSington: NSObject {

    /// 提示视图自动消失时间(默认4秒，若为0，则不自动消失)
    public var autoDismissSeconds:Float = 4.0
    
    /// 截图编辑控制器  - 标题
    public var editControllerTitle:String = "截图编辑"
    
    /// 截图编辑控制器  - 画笔颜色
    public var stokeColor:UIColor = .red
    
    /// 截图编辑控制器  - 画笔宽度
    public var stokeLineWidth:CGFloat = 4
    
    /// 提示视图消失回调
    public var hintViewDismissFinishBlock:( ()->Void )?
    
    /// 提示视图 - 分享回调
    public var hintViewShareBlock:( (_ shareImage:UIImage)->Void )?
    
    /// 提示视图 - 反馈回调(如果此block为空，则跳转到截图编辑界面)
    public var hintViewFeedbackBlock:( (_ feedbackImage:UIImage)->Void )?
    
    /// 截图编辑控制器  - 提交回调
    public var editControllerCommitBlock:( (_ finalImage:UIImage)->Void )?
    
    
    
    
    
    
    /// 单例
    public static var sharedInstance: LMScreenshotSington? = {
        
        let instance = LMScreenshotSington()
        
        instance.creatAppScreenshotNotification()
        
        print("LMScreenshotSington: 单例创建")

        return instance
    }()
    
    /// 销毁单例
    public func destroyInstance() {
        
        LMScreenshotSington.sharedInstance = nil
    }

    deinit {
        print("LMScreenshotSington: deinit")
    }
    
    
    
    /// 监听截屏通知
    private func creatAppScreenshotNotification() {

        NotificationCenter.default.addObserver(self,
                                               selector: #selector(screenshotsAction),
                                               name: UIApplication.userDidTakeScreenshotNotification,
                                               object: nil)
    }

    /// 移除截屏通知
    private func removeAppScreenshotNotification() {
        
        NotificationCenter.default.removeObserver(self, name: UIApplication.userDidTakeScreenshotNotification, object: nil)
    }

    /// 监听截屏通知处理事件
    @objc private func screenshotsAction() {
        
        print("LMScreenshotSington: 监听截屏通知")
        
        removeAppScreenshotNotification()
        
        let hintView:LMScreenshotHintView = LMScreenshotHintView.init(frame: CGRect.zero)
        hintView.autoDismissSeconds = autoDismissSeconds
        hintView.dismissFinishBlock = {
            
            LMScreenshotSington.sharedInstance?.creatAppScreenshotNotification()
            
            if LMScreenshotSington.sharedInstance?.hintViewDismissFinishBlock != nil {
                LMScreenshotSington.sharedInstance?.hintViewDismissFinishBlock!()
            }

        }
        hintView.showView()
        
    }


}
